package cn.com.customer.manager.ui.customer.customerList

import android.os.Build
import androidx.annotation.RequiresApi
import cn.com.customer.manager.bean.CustomerReiveInfo
import cn.com.customer.manager.bean.PrivateCustomer
import cn.com.customer.manager.bean.RequestBean
import cn.com.customer.manager.bean.StickyItem
import cn.com.customer.manager.http.BaseApi
import cn.com.customer.manager.http.subscriber.TipRequestSubscriber
import com.xuexiang.xhttp2.XHttp
import com.xuexiang.xhttp2.model.ApiResult

class CustomerPresenter constructor(view: CustomerContract.View) : CustomerContract.Presenter {
    val mView: CustomerContract.View = view
    val request = XHttp.custom()
    override fun getData(params: MutableMap<String, String>) {
        request.call(request.create(BaseApi.Customer::class.java)
                .customerList(RequestBean(params)))
                .subscribeWith(object : TipRequestSubscriber<ApiResult<CustomerReiveInfo>?>() {
                    override fun onSuccess(apiResult: ApiResult<CustomerReiveInfo>?) {
                        apiResult?.let {
                            if (it.data != null) {
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                    mView.setData(initStickyItem(it.data.privateCustomers), initStickyItem(it.data.publicCustomers))
                                }
                            }
                        }
                    }
                })
    }

    override fun setBelongPublic(params: MutableMap<String, String>) {
        request.call(request.create(BaseApi.Customer::class.java)
                .customerBelongPublic(RequestBean(params)))
                .subscribeWith(object : TipRequestSubscriber<String?>() {
                    override fun onSuccess(apiResult: String?) {
                        apiResult?.let {
                            if (it != null) {
                                mView.belongPublicSuccess()
                            }
                        }
                    }
                })
    }

    @RequiresApi(Build.VERSION_CODES.N)
    private fun initStickyItem(list: List<PrivateCustomer>): List<StickyItem> {
        var data: MutableList<StickyItem> = mutableListOf()
        var map = list.groupBy {
            it.companyName
        }
        map.forEach { (s, list) ->
            var value = StickyItem(s)
            data.add(value)
            list.forEach {
                data.add(StickyItem(it))
            }
        }
        return data
    }

    override fun start() {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }
}